package com.dd.shop4j.common.helper;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.dd.shop4j.common.helper.Table.Column;

/**
 * Mysql的自动生成帮助类
 * 
 * @author tangshu
 * 
 */
public class MySqlHelper extends AbstractSQLHepler implements ISQLHelper {

	/**
	 * 构造函数，主要是给tables初始化值
	 */
	public MySqlHelper() {
		String dirver = "com.mysql.jdbc.Driver", url = "jdbc:mysql://localhost:3306/shop4j", username = "root", password = "";
		JdbcCommon common = new JdbcCommon(dirver, url, username, password);
		List<Map<String, Object>> items = common
				.queryBySql("SELECT TABLE_NAME,TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? and TABLE_NAME like ?"
						, database, table_fix + "%");
		IDialect dialect = new MySqlDialect();
		for (Map<String, Object> item : items) {
			Table table = new Table((String) item.get("TABLE_NAME"),
					(String) item.get("TABLE_COMMENT"), dialect);
			List<Map<String, Object>> colItems = common.queryBySql("SELECT COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,COLUMN_KEY,COLUMN_COMMENT,EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION"
					, database, (String) item.get("TABLE_NAME"));
			for (Map<String, Object> colItem : colItems) {
				Column column = table.new Column();
				column.setName((String)colItem.get("COLUMN_NAME"));
				column.setType((String)colItem.get("DATA_TYPE"));
				BigInteger length = (BigInteger)colItem.get("CHARACTER_MAXIMUM_LENGTH");
				if (length != null) {
					column.setLength(length.intValue());
				}
				column.setCommect((String)colItem.get("COLUMN_COMMENT"));
				column.setDefaultValue((String)colItem.get("COLUMN_DEFAULT"));
				column.setPk("PRI".equals((String)colItem.get("COLUMN_KEY")));
				column.setNullable("YES".equals((String)colItem.get("IS_NULLABLE")));
				column.setAuto("auto_increment".equals((String)colItem.get("EXTRA")));
				table.addColumn(column);
			}
			tables.add(table);
		}
	}
	
}
